package com.zby.scms.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Joiner;
import com.zby.scms.entity.Competition;
import com.zby.scms.entity.Team;
import com.zby.scms.service.CompetitionService;
import com.zby.scms.service.TeamService;
import com.zby.scms.utils.BaseResult;
import com.zby.scms.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * 队伍实体(Team)表控制层
 *
 * @author zhangboyi
 * @since 2020-01-16 10:46:55
 */
@Api(tags = "队伍实体(Team)")
@RestController
@RequestMapping ("team")
public class TeamController {
    /**
     * 服务对象
     */
    @Autowired
    private TeamService teamService;

    @Autowired
    private CompetitionService competitionService;

    private Logger logger = LoggerFactory.getLogger(TeamController.class);

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation("根据id查询 ")
    @GetMapping ("selectOne/{id}")
    public Team selectOne(@ApiParam(value = "队伍id ID") @PathVariable ("id") Integer id) {
        return this.teamService.queryById(id);
    }

    /**
     * 添加队伍
     * */
    @ApiOperation("添加队伍")
    @PostMapping ("addTeam")
    public BaseResult<Team> addTeam(Team team){
        if(team.getCompeteid()==null){
            return ResultUtil.error(400, "项目不能为空");
        }else if(competitionService.queryById(team.getCompeteid())==null){
            return ResultUtil.error(400, "项目不存在");
        }

        return ResultUtil.success(teamService.addTeam(team));
    }

    @ApiOperation("解散队伍")
    @DeleteMapping("deleteTeam")
    public BaseResult<Team> deleteTeam(Integer teamId, String leaderUserId){
        //队伍不存在的时候
        Team team = teamService.queryById(teamId);
        if(team==null){
            return ResultUtil.error(400, "队伍不存在");
        }
        if(!leaderUserId.equals(team.getLeaderuserid())){
            //不是队长的时候
            logger.info("team.getLeaderuserid():"+team.getLeaderuserid()+"。leaderUserId:"+leaderUserId);
            return ResultUtil.error(401, "您不是队长，无权解散队伍");
        }
        logger.info("队伍存在，且为队伍队长，成功删除队伍");
        //通过teamid删除
        teamService.deleteById(teamId);
        return ResultUtil.success("成功解散该队伍！",team);



    }

    @ApiOperation("退出队伍" )
    @PutMapping("exitTeam")
    public BaseResult<Team> exitTeam(Integer teamId, String userid){

        //查询队伍是否存在
        Team team = teamService.queryById(teamId);


        if(team==null){
            return ResultUtil.error(400, "队伍不存在");
        }

        List<String> memberlist = Arrays.asList(team.getMeberlist().split(","));
        List<String> result = new ArrayList<>(memberlist);

        logger.info("原队伍的result为："+result.toString());

        int ismember = ismemberlist(result,userid);
        //查询该用户id是否存在与memberlist中
        if(ismember==-1){
            //不存在，则返回"您不在队伍中"
            return ResultUtil.error(401, "您不在队伍中");
        }
        if(userid.equals(team.getLeaderuserid())){
            //如果是队长退出队伍，则解散
            teamService.deleteById(teamId);
            return ResultUtil.success(team);
        }

        //如果不是队长，且在队伍中，则修改数据库
        result.remove(ismember);
/*        Iterator<String> iterator = result.iterator();
        while(iterator.hasNext()){
            String item = iterator.next();
            if(item.equals(userid)){
                logger.info("item为:"+item);
                iterator.remove();
            }
        }*/
//        logger.info(bo);
/*        for(int i=result.size();i>=0;i--){
            Iterator<String> iterator = result.iterator();
            while(iterator.hasNext()){
                String item = iterator.next();
                if(item.equals(userid)){
                    logger.info("删除的元素为："+item);
                    iterator.remove();
                    break;
                }
            }
        }*/

        logger.info("退出队伍后的result为："+result.toString());
         //修改数据库
        team.setMeberlist(Joiner.on(",").join(result));
        return ResultUtil.success("成功退出队伍",teamService.updateTeam(team));

    }

    /*判断是否存在队伍中,返回元素下标
    * */

    public int ismemberlist(List<String> result,String userid){

        for(int i=result.size()-1;i>=0;i--){
            if(result.get(i).equals(userid)){
                logger.info(result.get(i)+"  and "+ i);
                return i;

            }

        }
        return -1;

    }



/**
 * 查询队伍：
 * 1、通过查询所在的队伍，去查询并显示自己所参与的项目(传入参数为：userId,接收参数为memberlist)
 * 2、管理员查看所有队伍，入参teamName、competetionid
 * */


    @ApiOperation("查询所有队伍")
    @GetMapping("queryAll")
    public BaseResult<List<Team>> queryAll(Team team,Integer pageNum, Integer pageSize){
        if (pageNum == null&&pageSize == null){
            logger.info("请求的参数不能为空");
            return ResultUtil.error(400, "请求的参数不能为空");
        }
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<Team> pageInfo = new PageInfo<>(teamService.queryAll(team));

        return ResultUtil.success(
                pageInfo.getList(),
                pageInfo.getPageNum(),
                pageInfo.getPageSize(),
                pageInfo.getTotal());
    }


    @ApiOperation("查询自己所参加的竞赛：分页有点瑕疵" )
    @GetMapping("queryByUserId" )
    public BaseResult<List<Competition>> queryByUserId(String userId,Integer pageNum, Integer pageSize){
        //查询
        if (pageNum == null||pageSize == null){
            logger.info("请求的参数不能为空");
            return ResultUtil.error(400, "请求的参数不能为空");
        }

        //查询出该用户所在的队伍
        Team team = new Team();
        team.setMeberlist(userId);
        List<Team> teams = teamService.queryAll(team);
/*        if(teams.size()==0){
            return ResultUtil.error("数据为空");
        }*/

        //获取竞赛项目ID：teams.get(1).getCompeteid();


        //通过获取的竞赛项目id查询竞赛项目

        //竞赛---队伍：1-n

        //接收分页信息
        PageHelper.startPage(pageNum, pageSize);
        //存储数据
        List<Competition> competitionList = new ArrayList<>();

        Competition competition ;
        for(int i = 0 ; i < teams.size(); i++){
            //获取竞赛项目ID：teams.get(1).getCompeteid();
            // 通过competeId获取竞赛信息
            competition = competitionService.queryById(teams.get(i).getCompeteid());
            competitionList.add(i,competition);
        }

        logger.info(competitionList.toString());
//

        PageInfo<Competition> pageInfo = new PageInfo<>(competitionList);

        return ResultUtil.success(
                pageInfo.getList(),
                pageInfo.getPageNum(),
                pageInfo.getPageSize(),
                pageInfo.getTotal());
    }







    /**判断队伍是否存在
     *
     * */



/*
    public Team is(Integer teamId){
        Team team = teamService.queryById(teamId);

    }
*/



}